<template>
  <el-dialog
    ref="adjustProjectDialogRef"
    v-dialogDrag
    :append-to-body="true"
    :modal-append-to-body="true"
    :modal="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="跨项目调整"
    class="pms-zr-dialog"
    v-bind="$attrs"
    v-on="$listeners"
    width="80%"
    @close="()=>{cancel()}"
  >
    <div style="color: #eb4b4b;padding-bottom: 15px">PC端仅支持对无标签ID物资进行跨项目调整（其他项目物资调拨至本项目）操作，有标签ID物资请在工程管理APP-项目查询-到货确认模块下进行操作。</div>
    <el-form ref="form" :model="form" label-width="160px" size="mini" :inline="true" style="margin-bottom: 10px;">
      <el-row :gutter="24">
        <el-col :span="5" v-if="manageMode === '02'">
          <el-form-item label="批量子项目编码" style="width: 100%;display: flex;" :rules="{ required: true}">
              <el-select v-model="form.subPrjId" placeholder="请输入并选择" filterable :popper-append-to-body="false" @change="handleSubPrjId">
                  <el-option
                      v-for="(item,index) in subPrjIdArray"
                      :key="index"
                      :label="item.PRJCODE"
                      :value="item.SUBPRJID"
                  />
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="manageMode === '02'? 5:6">
          <el-form-item label="物料编码" style="width: 100%;display: flex;" :rules="{ required: true}">
              <el-select v-model="form.code" placeholder="请输入并选择" filterable :popper-append-to-body="false">
                  <el-option
                      v-for="(item,index) in optionArray"
                      :key="index"
                      :label="item.categoryCode"
                      :value="item.categoryCode"
                  />
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="manageMode === '02'? 5:6">
          <el-form-item label="物料名称" style="width: 100%;display: flex;" :rules="{ required: true}">
             <el-select v-model="form.code" placeholder="请输入并选择" filterable :popper-append-to-body="false">
                 <el-option
                     v-for="(item,index) in optionArray"
                     :key="index"
                     :label="item.categoryName"
                     :value="item.categoryCode"
                 />
             </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="manageMode === '02'? 5:6">
          <el-form-item label="项目编码" style="width: 100%;display: flex;">
            <el-input v-model="form.projectCode" class="pms-zr-input" />
          </el-form-item>
        </el-col>
        <el-col :span="manageMode === '02'? 4:6 " style="text-align: right;padding-top: 5px">
          <el-button size="mini" class="pms-zr-button-primary" @click="doSearch" style="background: #eb4b4b !important;color: #FFF !important;">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div style="padding: 10px;border: 1px solid #ededed">
        <div style="display: flex;padding-bottom: 10px;align-items: center"><i class="item_icon" />可调整项目范围</div>
        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            max-height="400px"
            border
            row-key="sourceAssetCode"
            style="width: 100%;"
            :header-cell-style="{
                background: '#F5F5F5',
                color: '#333333',
                fontWeight:500
              }"
        >
            <el-table-column width="50" align="center">
                <template slot-scope="scope">
                    <el-radio class="radio" :label="scope.row" v-model="currentRow"><div></div></el-radio>
                </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="序号" width="50" />
            <el-table-column align="center" prop="prjCode" label="项目编码" />
            <el-table-column align="center" prop="prjName" label="项目名称" min-width="200"/>
            <el-table-column align="center" prop="transferNum" label="可调整数量" />
        </el-table>
        <pagination
            v-if="pageParam.total > 10"
            :total="pageParam.total"
            :page.sync="pageParam.pageNum"
            :limit.sync="pageParam.pageSize"
            @pagination="doSearch"
        />
    </div>
      <div style="display: flex;margin-top: 15px">
          <div style="width: 80px"><span style="color: #eb4b4b;margin-right: 3px ">*</span>调整数量：</div>
          <el-input
              style="width: 150px"
              v-model="adjustNum"
              type="number"
              class="pms-custom"
              placeholder="请输入"
          />
      </div>
    <div slot="footer" class="dialog-footer">
      <el-button class="pms-zr-button" size="small" @click="cancel" style="margin-right: 10px !important;">取 消</el-button>
      <el-button class="pms-zr-button-primary" size="small" v-debounce="save" style="background: #eb4b4b !important;color: #FFF !important;">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {disableScroll, enableScroll, getQueryObject, msgInfoEl,clonePage} from "@/utils";
import SysConst from "@/common/const";
import {
    doSaveMaterialTransferInfo,
    getTransferUnitAccByMaterialCode,
    queryDesignMateListByPrjId, queryPlSonPrjCode,
    queryTransferList
} from "@/api/material";
import {checkIsNeedAdjustPrjFlow, startAdjustPrjFlow} from "@/api/adjustProject";
export default {
    name: 'AdjustProjectDialog',
    components: {},
    props: {
        orgId:{
            type:String,
            default:''
        }
    },
    data() {
        return {
            form: {
              code: '',
              projectCode: '',
              subPrjId:'',
            },
            tableData:[],
            optionArray:[],
            currentRow:'',
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            adjustNum:'',
            prjId:'',
            manageMode:'01',
            loading:false,
            subPrjIdArray:[],
            btnLoading:false,
        }
    },
    created() {
        const { prjId,manageMode } = getQueryObject();
        this.prjId = prjId;
        this.manageMode = manageMode;
    },
    mounted() {
        if(this.manageMode === '02'){
            this.queryPlSonPrjCode();
        }else{
            this.getDesignMateListByPrjId();
        }
    },
    methods: {
        handleSubPrjId(){
            this.getDesignMateListByPrjId();
            this.form.code = '';
            this.tableData = [];
        },
        queryPlSonPrjCode(){
            queryPlSonPrjCode(this.prjId).then((res)=>{
                this.subPrjIdArray=res.data;
            })
        },
        getDesignMateListByPrjId(){
            const data={
                prjId:this.prjId,
                subPrjId:this.form.subPrjId,
            }
            queryDesignMateListByPrjId(data).then((res)=>{
                this.optionArray=res.data;
            })
        },
        cancel() {
            this.$emit('update:visible', false)
        },
        checkBindNumOne(){
            if(!this.adjustNum){
                msgInfoEl({
                    type:'error',
                    message:'请输入调整数量',
                })
                return Promise.reject('error')
            }
        },
        checkBindNumTwo(){
            if(+this.adjustNum <= 0){
                msgInfoEl({
                    type:'error',
                    message:'调整数量应大于0',
                })
                return Promise.reject('error')
            }
        },
        async checkBindNumThree(){
            console.log(1111,this.currentRow)
            const params={
                materialCode:this.form.code,
                retreatAmount:this.adjustNum,
            }
            await getTransferUnitAccByMaterialCode(params).then((res)=>{
                if(+res.code !== 200){
                    return Promise.reject('error')
                }
            }).catch(()=>{
                return Promise.reject('error')
            })
        },
        async checkBindNumFour(){
            if(+this.adjustNum > +this.currentRow.transferNum){
                msgInfoEl({
                    type:'error',
                    message:'填写的调整数量已超过可调整数量，请重新输入！',
                })
                return Promise.reject('error')
            }
        },
        async save() {
            console.log(123,this.btnLoading)
            if(this.btnLoading){
                return;
            }
            this.btnLoading= true;
            setTimeout(()=>{
                this.btnLoading=false
            },5000)
            if(!this.currentRow){
                msgInfoEl({
                    type:'error',
                    message:'请选择一个调整项目',
                })
            }else {
                await this.checkBindNumOne();
                await this.checkBindNumTwo();
                await this.checkBindNumThree();
                await this.checkBindNumFour();
                //调接口判断是否进行跨项目审核操作
                this.checkNeedAdjust();
            }
        },
        checkNeedAdjust(){
            let params={
                oldPrjId: this.currentRow.prjId,
                newPrjId: this.prjId,
                categoryCode: this.form.code,
                transferNum: this.adjustNum,
                subPrjId:this.form.subPrjId,
                assetLabelId:'',
            }
            checkIsNeedAdjustPrjFlow(params).then((res)=>{
                if(+res.code === 200){
                    if(+res.data === 1){
                        this.dialogTitle(params);
                    }else{
                        let params1={
                            oldPrjId: this.currentRow.prjId,
                            newPrjId: this.prjId,
                            categoryCode: this.form.code,
                            transferNum: this.adjustNum,
                            subPrjId:this.form.subPrjId,
                        }
                        doSaveMaterialTransferInfo(params1).then((res1)=>{
                            if(+res1.code === 200){
                                this.$message.success('操作成功')
                                setTimeout(()=>{
                                    this.saveEmit();
                                },1000)
                            }
                        })
                    }
                }
            })
        },
        //跨项目审核提示
        dialogTitle(params){
            this.$confirm('发起跨项目调整操作需双方经理审批?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                closeOnClickModal: false
            }).then(async () => {
                startAdjustPrjFlow(params).then((res)=>{
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    }
                    const url = `${process.env.VUE_APP_ZHONGRUAN_URL}adjustProject?workItemId=${res.data}&type=todo&status=1`
                    window.open(url)
                    clonePage()
                })
            }).catch(() => {
                console.log('点取消了')
            })
        },
        saveEmit(){
            if(this.manageMode === '03' || this.manageMode === '04'){
                this.$emit('addApplyDetail')
            }else{
                this.$emit('doSaveApplyBySite')
            }
            this.$emit('update:visible', false)
        },
        doSearch(item) {
            if(this.form.code){
                this.loading=true;
                let params={
                    orgId:this.orgId,
                    prjId:this.prjId,
                    categoryCode: this.form.code,
                    prjParam: this.form.projectCode,
                    queryType: "1",
                    pageNum: item?.page || SysConst.CURRENT_PAGE  ,
                    pageSize: item?.limit || SysConst.PAGESIZE
                }
                console.log(1111,params,item)
                queryTransferList(params).then((res)=>{
                    if(+res.code === 200){
                        this.tableData = res.data?.rows
                        this.pageParam.total = res.data?.total || 0
                        this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                        this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
                    }
                }).finally(()=>{
                    this.loading=false;
                })
            }else{
                msgInfoEl({
                    type:'error',
                    message:'请选择调整的物料编码',
                })
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.item_icon {
    display: block;
    width: 5px;
    background: rgb(235, 75, 75);
    height: 18px;
    margin-right: 10px;
    border-radius: 10px;
}
</style>
